﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Controls;
using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.esriSystem;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.Geometry;
using PlanningGIS.DataConvert.model;
using PlanningGIS.Framework.Controls;
using System.Collections;
using ESRI.ArcGIS.DataSourcesGDB;
using PlanningGIS.ArcGIS.Custom;
using PlanningGIS.Engine.Controls;
using PlanningGIS.Win.Controls;
using PlanningGIS.ArcGIS;
using PlanningGIS.Util.Collections;
using PlanningGIS.Util.Convertor;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Log;
using PlanningGIS.Framework.Config;

namespace PlanningGIS.DataConvert.form
{
    /// <summary>
    ///作用：矢量数据入库界面
    /// </summary>
    public partial class FrmDlgDataImport : Office2007Form
    {
        /// <summary>
        /// 
        /// </summary>
        private FrmSelRule frmSelectRule;
        /// <summary>
        /// 
        /// </summary>
        private DataImportRule dataImportRule;
        /// <summary>
        /// 
        /// </summary>
        private DataMatchRule dataMatchRule;
        /// <summary>
        /// 
        /// </summary>
        private List<IFeatureClass> pFeatClsLstSource;
        /// <summary>
        /// 
        /// </summary>
        private List<IFeatureClass> pFeatClsLstTarget;
        /// <summary>
        /// 
        /// </summary>
        private DlgDataImportConstruct dlgDataImportConstruct;
        /// <summary>
        /// 
        /// </summary>
        private DlgDataImport dlgDataImport;
        /// <summary>
        /// 
        /// </summary>
        List<DlgDataConvert> dlgDataConverts;
        /// <summary>
        /// 
        /// </summary>
        DlgDataConvert dlgDataConvert;
        /// <summary>
        /// 是否正在入库中
        /// </summary>
        private bool doing = false;
        /// <summary>
        /// 是否被用户终止
        /// </summary>
        private bool breaked = false;
        /// <summary>
        /// 
        /// </summary>
        private IWorkspace pWorkSpace;
        /// <summary>
        /// 
        /// </summary>
        private bool refreshFieldRelation = true;
        
        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmDlgDataImport()
        {
            InitializeComponent();

            cboPrefix.SelectedIndex = 0;
            cboPostfix.SelectedIndex = 0;
        }
        

        #region 按代码入库

        /// <summary>
        /// 通过选择方案控件的打开工作空间按钮来改变目标工作空间
        /// </summary>
        /// <param name="pWs"></param>
        private void CmdDataConnectionChanged_Click(IWorkspace pWs)
        {
            pWorkSpace = pWs;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            frmSelectRule.RuleType = zjgisRuleType.dlgImpByCode;
            if (frmSelectRule.ShowDialog() != DialogResult.OK) return;
            RuleXml dataImportRuleBase = frmSelectRule.Rule;
            if (dataImportRuleBase != null && dataImportRuleBase is DataImportRule)
            {
                dataImportRule = dataImportRuleBase as DataImportRule;
                getRuleWorkspaceConnection1.RefreshWorkspaceConnection(dataImportRule);
            }
        }

        #endregion

        #region 按图层和字段的对应关系入库
        
        /// <summary>
        /// 选择入库目标数据
        /// </summary>
        /// <param name="datasetList"></param>
        private void CmdSelectDataOkTarget_Click(List<IDataNode> datasetList)
        {
            if (pFeatClsLstTarget == null)
            {
                pFeatClsLstTarget = new List<IFeatureClass>();
            }
            pFeatClsLstTarget.Clear();

            //改变了目标数据需要将树上的节点先清空，并且 List<DlgDataConvert>也要清空，重新匹配
            trvTarget.Nodes.Clear();
            dlgDataConverts = null;
            cboSource.Text = "";
            dataGridViewMatch.Rows.Clear();

            foreach (IDataNode datanode in datasetList)
            {
                IDataset dataset = datanode.Open();
                if (dataset.Type == esriDatasetType.esriDTFeatureClass)
                {
                    pFeatClsLstTarget.Add((IFeatureClass)dataset);

                    trvTarget.Nodes.Add(dataset.Name);
                }
            }
        }

        /// <summary>
        /// 自动匹配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnAutoMatch_Click(object sender, EventArgs e)
        {
            DlgDataImportMatch dlgDataImportMatch = new DlgDataImportMatch();
            dlgDataImportMatch.SetProcessBarMax = setSubPgbMax;
            dlgDataImportMatch.SetProcessBarCurrent = setSubPgbCurrent;
            dlgDataImportMatch.NeedDelete = chkDelete.Checked;
            dlgDataImportMatch.FeatClsListSource = pFeatClsLstSource;
            dlgDataImportMatch.FeatClsListTarget = pFeatClsLstTarget;

            dlgDataImportMatch.PreTarOrSur = (cboPrefix.SelectedIndex == 0);
            dlgDataImportMatch.Prefix = StringHelper.ConvertWRTNull(txtPrefix.Text);

            dlgDataImportMatch.PostTarOrSur =(cboPostfix.SelectedIndex ==0);
            dlgDataImportMatch.Postfix = StringHelper.ConvertWRTNull(txtPostfix.Text);

            if (dlgDataImportMatch.MatchAutomatic())
            {
                dlgDataConverts = dlgDataImportMatch.DlgDataConverts;
                GiveConvert2TreeNode();
                MsgHelper.ShowInfomationMsgbox("匹配完成！");
            }
            else
            {
                MsgHelper.ShowWarningMsgbox("匹配失败，详细原因请查看日志！");
            }
        }

        /// <summary>
        /// 给树上每一个节点附上相应的DlgDataConvert作为Tag，以便后面修改
        /// </summary>
        private void GiveConvert2TreeNode()
        {
            foreach (TreeNode treeNode in trvTarget.Nodes)
            {
                foreach (DlgDataConvert dlgDataConvert in dlgDataConverts)
                {
                    if (treeNode.Text == (dlgDataConvert.TargetFeatCls as IDataset).Name)
                    {
                        treeNode.Tag = dlgDataConvert;
                        break;
                    }
                }
            }
        }

        /// <summary>
        /// 点击树节点事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void trvTarget_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            dlgDataConvert = null;

            if (e.Node.Tag == null ||( e.Node.Tag is DlgDataConvert)==false )
            {
                MsgHelper.ShowWarningMsgbox("请先执行自动匹配或者按规则匹配操作！\n注意：如果改变了目标数据需要重新执行以上操作！");
                return;
            }

            dlgDataConvert = e.Node.Tag as DlgDataConvert;
            
            if (dlgDataConvert.SourceFeatCls != null)
            {
                if (cboSource.Items.Count > 0)
                {
                    bool hasFound = false;
                    for (int i = 0; i < cboSource.Items.Count; i++)
                    {
                        if (cboSource.Items[i].ToString() == (dlgDataConvert.SourceFeatCls as IDataset).Name)
                        {
                            hasFound = true;
                            refreshFieldRelation = false;
                            cboSource.Text =(dlgDataConvert.SourceFeatCls as IDataset).Name;
                            refreshFieldRelation = true;
                            break ;
                        }
                    }
                    if (!hasFound)
                    {
                        cboSource.Text = "";
                    }
                }
            }
            else
            {
                cboSource.Text = "";
            }

            if (dlgDataConvert.FieldRelation != null && dlgDataConvert.FieldRelation.Count > 0)
            {
                dataGridViewMatch.Rows.Clear();
                foreach (DictionaryEntry de in dlgDataConvert.FieldRelation)
                {
                    dataGridViewMatch.Rows.Add();
                    refreshFieldRelation = false;
                    dataGridViewMatch.Rows[dataGridViewMatch.Rows.Count - 1].Cells["clmTarget"].Value = de.Key;
                    dataGridViewMatch.Rows[dataGridViewMatch.Rows.Count - 1].Cells["clmSource"].Value = de.Value;
                    refreshFieldRelation = true;
                }
            }
        }

        /// <summary>
        /// 图层匹配变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboSource_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (dlgDataConvert == null) return;

            clmSource.Items.Clear();
            clmSource.Items.Add("");

            foreach (IFeatureClass pFeatCls in pFeatClsLstSource)
            {
                if ((pFeatCls as IDataset).Name == cboSource.Text)
                {
                    dlgDataConvert.SourceFeatCls = pFeatCls;

                    for (int i = 0; i < pFeatCls.Fields.FieldCount; i++)
                    {
                        IField pField = pFeatCls.Fields.get_Field(i);
                        if (pField.Editable && pField.Type !=esriFieldType.esriFieldTypeGeometry) clmSource.Items.Add(pField.Name);
                    }

                    if (!refreshFieldRelation) continue;

                    foreach (DataGridViewRow dataGridviewRow in dataGridViewMatch.Rows)
                    {
                        dataGridviewRow.Cells["clmSource"].Value = "";
                        for (int i = 0; i < clmSource.Items.Count; i++)
                        {
                            if (clmSource.Items[i].ToString().ToUpper () == dataGridviewRow.Cells["clmTarget"].Value.ToString ().ToUpper ())
                            {
                                dataGridviewRow.Cells["clmSource"].Value = clmSource.Items[i].ToString();
                                break;
                            }
                        }
                    }
                    break;
                }
            }
        }

        /// <summary>
        /// 字段匹配变化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewMatch_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (!refreshFieldRelation) return;
            if (dlgDataConvert == null) return;
            if (e.RowIndex < 0 || e.RowIndex >= dataGridViewMatch.Rows.Count) return;

            Hashtable fieldRelation = dlgDataConvert.FieldRelation;

            fieldRelation[dataGridViewMatch.Rows[e.RowIndex].Cells["clmTarget"].Value] =
                 StringHelper.ConvertWRTNull(dataGridViewMatch.Rows[e.RowIndex].Cells["clmSource"].Value);

            dlgDataConvert.FieldRelation = fieldRelation;
        }

        /// <summary>
        /// 保存为规则
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSaveToRule_Click(object sender, EventArgs e)
        {
            try
            {
                if (pFeatClsLstSource == null || pFeatClsLstSource.Count == 0)
                {
                    MsgHelper.ShowWarningMsgbox("请选择数据源！");
                    return;
                }

                if (pFeatClsLstTarget == null || pFeatClsLstTarget.Count == 0)
                {
                    MsgHelper.ShowWarningMsgbox("请选择目标数据！");
                }

                if (dlgDataConverts == null || dlgDataConverts.Count == 0)
                {
                    MsgHelper.ShowWarningMsgbox("请先进行匹配！");
                    return;
                }

                FrmText box = new FrmText();
                box.Title = "新建入库规则";
                if (box.DialogResult != System.Windows.Forms.DialogResult.OK) return;
                string ruleName = box.Value;
                if (ruleName == "")
                {
                    MsgHelper.ShowWarningMsgbox("规则名不能为空！");
                    return;
                }

                List<DataMatchRule> dataMatchRules = ConvertHelper.DataConvert.DataMatchtRules;
                if (dataMatchRules == null) dataMatchRules = new List<DataMatchRule>();

                List<DataMatchRule> temp = ListHelper.GetEnumeratorItems(ConvertHelper.DataConvert.DataMatchtRules,
                                                   "RuleName", ruleName);
                if (temp.Count > 0)
                {
                    MsgHelper.ShowInfomationMsgbox("规则名称重复，请修改！");
                    return;
                }

                DataMatchRule dataMatchRule = new DataMatchRule();
                dataMatchRule.RuleName = ruleName;

                List<DlgTargetMatchFeatureClass> dlgTargetMatchFeatureClasses = new List<DlgTargetMatchFeatureClass>();
                dataMatchRule.dlgTargetMatchFeatureClass = dlgTargetMatchFeatureClasses;

                foreach (DlgDataConvert dlgDataConvert in dlgDataConverts)
                {
                    DlgTargetMatchFeatureClass dlgTargetMatchFeatureClass = new DlgTargetMatchFeatureClass();

                    if (dlgDataConvert.SourceFeatCls == null)
                    {
                        continue;
                    }

                    dlgTargetMatchFeatureClass.SourceFeatClsName = (dlgDataConvert.SourceFeatCls as IDataset).Name;
                    dlgTargetMatchFeatureClass.FeatureClassName = (dlgDataConvert.TargetFeatCls as IDataset).Name;
                    dlgTargetMatchFeatureClass.FeatureClassAliasName = dlgDataConvert.TargetFeatCls.AliasName;

                    if (dlgDataConvert.TargetFeatCls.FeatureType == esriFeatureType.esriFTAnnotation)
                        dlgTargetMatchFeatureClass.GeometryType = "注记";
                    else if (dlgDataConvert.TargetFeatCls.FeatureType == esriFeatureType.esriFTSimple)
                        dlgTargetMatchFeatureClass.GeometryType = Convertor.GetGeometryType(dlgDataConvert.TargetFeatCls.ShapeType);
                    else
                    {
                        MsgHelper.ShowWarningMsgbox("该入库功能不支持[" + (dlgDataConvert.TargetFeatCls as IDataset).Name +
                            "]数据的要素类型：[" + dlgDataConvert.TargetFeatCls.FeatureType.ToString() + "]");
                        continue;
                    }

                    //dlgTargetMatchFeatureClass.GeometryType 

                    if (dlgDataConvert.FieldRelation == null || dlgDataConvert.FieldRelation.Count == 0) continue;

                    List<AttrField> attrFields = new List<AttrField>();

                    foreach (DictionaryEntry de in dlgDataConvert.FieldRelation)
                    {
                        AttrField attrField = new AttrField();

                        attrField.TargetFieldName = de.Key.ToString();
                        attrField.SourceFieldName = de.Value.ToString();

                        int idxField = dlgDataConvert.TargetFeatCls.FindField(attrField.TargetFieldName);
                        if (idxField == -1) continue;

                        IField pField = dlgDataConvert.TargetFeatCls.Fields.get_Field(idxField);

                        string fieldType = Convertor.GetFieldType(pField.Type);
                        if (fieldType == null) continue;

                        attrField.Type = fieldType;
                        attrField.length = pField.Length.ToString();
                        attrField.precision = pField.Precision.ToString();
                        attrField.scale = pField.Scale.ToString();

                        attrFields.Add(attrField);

                    }
                    dlgTargetMatchFeatureClass.attrFields = attrFields;
                    dlgTargetMatchFeatureClasses.Add(dlgTargetMatchFeatureClass);
                }



                dataMatchRules.Add(dataMatchRule);
                
                ConfigHelper.SaveObject<DataBuilding>(RuleConfig.DataBuilding, "Rule");
                MsgHelper.ShowInfomationMsgbox("保存完毕！");

            }
            catch (Exception ex)
            {
                MsgHelper.ShowErrorMsgbox("保存规则失败：" + ex.Message);
            }
        }

        /// <summary>
        /// 按规则匹配
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMatchByRule_Click(object sender, EventArgs e)
        {
            dataMatchRule = null;

            frmSelectRule.RuleType = zjgisRuleType.dlgImpByLyr;

            RuleXml dataImportRuleBase;
            dataImportRuleBase = frmSelectRule.Rule;

            if (frmSelectRule.ShowDialog() != DialogResult.OK) return;

            if (dataImportRuleBase != null && dataImportRuleBase is DataMatchRule)
            {
                dataMatchRule = dataImportRuleBase as DataMatchRule;
            }

            if (dataMatchRule == null) return;

            DlgDataImportMatch dlgDataImportMatch = new DlgDataImportMatch();
            dlgDataImportMatch.SetProcessBarMax = setSubPgbMax;
            dlgDataImportMatch.SetProcessBarCurrent = setSubPgbCurrent;
            dlgDataImportMatch.NeedDelete = chkDelete.Checked;
            dlgDataImportMatch.FeatClsListSource = pFeatClsLstSource;
            dlgDataImportMatch.FeatClsListTarget = pFeatClsLstTarget;

            //dlgDataImportMatch.PreTarOrSur = (cboPrefix.SelectedIndex == 0);
            //dlgDataImportMatch.Prefix = StringUtility.ConvertWRTNull(txtPrefix.ControlText);

            //dlgDataImportMatch.PostTarOrSur = (cboPostfix.SelectedIndex == 0);
            //dlgDataImportMatch.Postfix = StringUtility.ConvertWRTNull(txtPostfix.ControlText);

            if (dlgDataImportMatch.MatchByRule(dataMatchRule))
            {
                dlgDataConverts = dlgDataImportMatch.DlgDataConverts;
                GiveConvert2TreeNode();
                MsgHelper.ShowInfomationMsgbox("匹配完成！");
            }
            else
            {
                MsgHelper.ShowWarningMsgbox("匹配失败，详细原因请查看日志！");
            }

        }

        #endregion

        #region Private functions
        /// <summary>
        /// 
        /// </summary>
        /// <param name="showOrNot"></param>
        private void showLoading(bool showOrNot)
        {
            //picLoading.Visible = showOrNot;
            //progressBarSub.Visible = !showOrNot;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="max"></param>
        private void setSubPgbMax(int max)
        {
            progressBarSub.Maximum = max;
            progressBarSub.Minimum = 0;
            progressBarSub.Value = 0;
            Application.DoEvents();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        private void setSubPgbCurrent(int current)
        {
            //if (current <= progressBarSub.Maximum)
            //{
            //    progressBarSub.Value = current;
            //}
            //else
            //{
            //    progressBarSub.Value = progressBarSub.Maximum;
            //}
            //Application.DoEvents();

            if (current <= progressBarSub.Maximum)
            {
                progressBarSub.Value = (int)current;

                double dRate = current * 100.0 / progressBarSub.Maximum;
                int iRate = (int)Math.Floor(dRate);
                progressBarSub.TextVisible = true;
                progressBarSub.Text ="分进度：" +  current.ToString() + "/" + progressBarSub.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                //dataGridViewX1.UseWaitCursor = true;
            }
            else
            {
                progressBarSub.Value = (int)progressBarSub.Maximum;
                progressBarSub.TextVisible = false;
                //dataGridViewX1.UseWaitCursor = false;
            }
            progressBarSub.Update();
            if (progressBarSub.Maximum < 200)
                Application.DoEvents();
            else
                if (current % (progressBarSub.Maximum / 100) == 0) Application.DoEvents();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="max"></param>
        private void setAllPgbMax(int max)
        {
            progressBarAll.Maximum = max;
            progressBarAll.Minimum = 0;
            progressBarAll.Value = 0;
            Application.DoEvents();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="current"></param>
        private void setAllPgbCurrent(int current)
        {
            //if (current <= progressBarAll.Maximum)
            //{
            //    progressBarAll.Value = current;
            //}
            //else
            //{
            //    progressBarAll.Value = progressBarAll.Maximum;
            //}
            //Application.DoEvents();

            if (current <= progressBarAll.Maximum)
            {
                progressBarAll.Value = (int)current;

                double dRate = current * 100.0 / progressBarAll.Maximum;
                int iRate = (int)Math.Floor(dRate);
                progressBarAll.TextVisible = true;
                progressBarAll.Text = "总进度：" + current.ToString() + "/" + progressBarAll.Maximum.ToString() + "(" + iRate.ToString() + "%)";

                //dataGridViewX1.UseWaitCursor = true;
            }
            else
            {
                progressBarAll.Value = (int)progressBarAll.Maximum;
                progressBarAll.TextVisible = false;
                //dataGridViewX1.UseWaitCursor = false;
            }
            progressBarAll.Update();
            if (progressBarAll.Maximum < 200)
                Application.DoEvents();
            else
                if (current % (progressBarAll.Maximum / 100) == 0) Application.DoEvents();
        }

        /// <summary>
        /// 选择入库数据源
        /// </summary>
        /// <param name="datasetList"></param>
        private void CmdSelectDataOk_Click(List<IDataNode> datasetList)
        {
            if (pFeatClsLstSource == null)
            {
                pFeatClsLstSource = new List<IFeatureClass>();
            }
            
            //按图层入库，需将对应数据源的组合框重新填过
            cboSource.Items.Clear();
            //加一行空的，没匹配时用
            cboSource.Items.Add("");

            if (datasetList == null || datasetList.Count == 0) return;

            pFeatClsLstSource.Clear();
            foreach (IDataNode datanode in datasetList)
            {
                IDataset dataset = datanode.Open();
                if (dataset == null) continue;
                if (dataset.Type == esriDatasetType.esriDTFeatureClass)
                {
                    pFeatClsLstSource.Add((IFeatureClass)dataset);
                    cboSource.Items.Add(dataset.Name);
                }
            }
        }

        #endregion

        #region Events
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataImport_Load(object sender, EventArgs e)
        {

            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
            SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲

            frmSelectRule = new FrmSelRule();
            frmSelectRule.TypeComboxVisable = false;

            selectGdbDataSource1.SelectDataOk = new CmdSelectDataOk(CmdSelectDataOk_Click);

            getRuleWorkspaceConnection1.DataConnectionChanged = new CmdDataConnectionChanged(CmdDataConnectionChanged_Click);

            selectGdbDataSource.SelectDataOk = new CmdSelectDataOk(CmdSelectDataOk_Click);
            selectGdbDataTarget.SelectDataOk = new CmdSelectDataOk(CmdSelectDataOkTarget_Click);
            
            this.dataGridViewMatch.DataError += new System.Windows.Forms.DataGridViewDataErrorEventHandler(ControlHelper.dataGridViewX_DataError);

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImport_Click(object sender, EventArgs e)
        {
            TabItem tabItem = tabControl1.SelectedTab;
            dlgDataImportConstruct = new DlgDataImportConstruct();

            //FrmNewLog frmNewLog = new FrmNewLog(OperateType.DataImport);

            progressBarAll.Value = 0;
            progressBarAll.Text = "";
            progressBarSub.Value = 0;
            progressBarSub.Text = "";

            try
            {
                switch (tabItem.Name)
                {
                    case "tbImportByCode":
                        #region 按代码入库
                        if (dataImportRule == null)
                        {
                            MsgHelper.ShowInfomationMsgbox("请选择规则！");
                            return;
                        }

                        if (dataImportRule.SourceFieldName == null || dataImportRule.SourceFieldName == "")
                        {
                            MsgHelper.ShowInfomationMsgbox("请设置入库依据字段！");
                            return;
                        }

                        if (pFeatClsLstSource == null || pFeatClsLstSource.Count == 0)
                        {
                            MsgHelper.ShowInfomationMsgbox("请设置数据源！");
                            return;
                        }

                        progressBarSub.Visible = true;
                        progressBarAll.Visible = true;
                        btnStop.Visible = true;

                        dlgDataImportConstruct.TargetWs = pWorkSpace;

                        dlgDataImportConstruct.DataImportRule = dataImportRule;
                        dlgDataImportConstruct.SetProcessBarMax = setSubPgbMax;
                        dlgDataImportConstruct.SetProcessBarCurrent = setSubPgbCurrent;
                        dlgDataImportConstruct.FeatClsListSource = pFeatClsLstSource;
                        dlgDataImportConstruct.IsCreateTargetFeatCls = chkCreateWs.Checked;
                        dlgDataImportConstruct.NeedDelete = chkDelete.Checked;

                        doing = true;

                        if (!dlgDataImportConstruct.Operate())
                        {
                            if (breaked)
                            {
                                LogHelper.WriteLog("入库被终止。\n");
                                MsgHelper.ShowInfomationMsgbox("入库操作被终止！");
                                breaked = false;
                            }
                            else
                            {
                                LogHelper.WriteErrLog("构造失败！！！\n");
                                MsgHelper.ShowWarningMsgbox("构造失败！详细信息请查看日志。");
                                //frmNewLog.IsSucceed = false;
                            }
                        }
                        else
                        {
                            dlgDataConverts = dlgDataImportConstruct.DlgDataConverts;

                            dlgDataImport = new DlgDataImport();
                            dlgDataImport.NeedValidate = chkValidate.Checked;
                            dlgDataImport.SourceCodeName = dataImportRule.SourceFieldName;// txtFcode.Text;
                            dlgDataImport.ShowLoadingProcessBar = showLoading;
                            dlgDataImport.SetProcessBarMax = setAllPgbMax;
                            dlgDataImport.SetProcessBarCurrent = setAllPgbCurrent;
                            dlgDataImport.FcodeRelationAnno = dlgDataImportConstruct.FcodeRelationAnno;
                            dlgDataImport.FcodeRelationPt = dlgDataImportConstruct.FcodeRelationPt;
                            dlgDataImport.FcodeRelationLn = dlgDataImportConstruct.FcodeRelationLn;
                            dlgDataImport.FcodeRelationPy = dlgDataImportConstruct.FcodeRelationPy;
                            dlgDataImport.FeatClsListSource = pFeatClsLstSource;
                            dlgDataImport.Task = dlgDataConverts;

                        }
                        #endregion

                        break;

                    case "tbImportByLyr":
                        #region 按图层入库

                        if (pFeatClsLstSource == null || pFeatClsLstSource.Count == 0)
                        {
                            MsgHelper.ShowWarningMsgbox("请选择数据源！");
                            return;
                        }

                        if (pFeatClsLstTarget == null || pFeatClsLstTarget.Count == 0)
                        {
                            MsgHelper.ShowWarningMsgbox("请选择目标数据！");
                        }

                        if (dlgDataConverts == null || dlgDataConverts.Count == 0)
                        {
                            MsgHelper.ShowWarningMsgbox("请先进行匹配！");
                            return;
                        }

                        #region 检测匹配信息是否完全
                        bool hasErr = false;

                        foreach (DlgDataConvert dlgDataConvert in dlgDataConverts)
                        {
                            if (dlgDataConvert.SourceFeatCls == null)
                            {
                                hasErr = true;
                                LogHelper.WriteErrLog("目标数据[" + (dlgDataConvert.TargetFeatCls as IDataset).Name + "]未设置数据源！");
                                continue;
                            }
                            bool hasFound = false;
                            foreach (IFeatureClass pFeatCls in pFeatClsLstSource)
                            {
                                if ((pFeatCls as IDataset).Name == (dlgDataConvert.SourceFeatCls as IDataset).Name)
                                {
                                    hasFound = true;
                                    break;
                                }
                            }
                            if (hasFound)
                            {
                                if (dlgDataConvert.FieldRelation == null || dlgDataConvert.FieldRelation.Count == 0)
                                {
                                    hasErr = true;
                                    LogHelper.WriteErrLog("目标数据[" + (dlgDataConvert.TargetFeatCls as IDataset).Name + "]未设置相应的字段匹配信息！");
                                }
                                else
                                {
                                    foreach (DictionaryEntry de in dlgDataConvert.FieldRelation)
                                    {
                                        if (de.Value.ToString () == "")
                                        {
                                            hasErr = true;
                                            LogHelper.WriteErrLog("目标数据[" + (dlgDataConvert.TargetFeatCls as IDataset).Name + "]的[" + 
                                                de.Key + "]字段未设置相应的源字段信息！");
                                        }
                                    }
                                }
                                
                            }
                            else
                            {
                                hasErr = true;
                                LogHelper.WriteErrLog("目标数据[" + (dlgDataConvert.TargetFeatCls as IDataset).Name + "]对应的数据源[" + 
                                    (dlgDataConvert.TargetFeatCls as IDataset).Name + "]已被移除！");
                                dlgDataConverts.Remove(dlgDataConvert);
                            }
                        }

                        if (hasErr && chkValidateMatch.Checked )
                        {
                            if (MsgHelper.ShowYesOrNoQueryMsgBox("匹配信息尚未配全，是否仍然执行入库操作？") == DialogResult.No) return;
                        }
                        #endregion

                        progressBarSub.Visible = true;
                        progressBarAll.Visible = true;
                        btnStop.Visible = true;

                        dlgDataImport = new DlgDataImport();
                        dlgDataImport.ShowLoadingProcessBar = showLoading;
                        dlgDataImport.SetProcessBarMax = setAllPgbMax;
                        dlgDataImport.SetProcessBarCurrent = setAllPgbCurrent;
                        dlgDataImport.Task = dlgDataConverts;
                        dlgDataImport.UseGP = chkUseGP.Checked;

                        #region 数据入库日志
                        //frmNewLog.SourceWS = (dlgDataConverts[0].SourceFeatCls as IDataset).Workspace;
                        //frmNewLog.TargetWS = (dlgDataConverts[0].TargetFeatCls as IDataset).Workspace;
                        //List<FeatCls> featCLses1 = new List<FeatCls>();
                        //foreach (DlgDataConvert dlgDataConvert in dlgDataConverts)
                        //{
                        //    FeatCls featCls = new FeatCls();
                        //    if (dlgDataConvert.SourceFeatCls == null) continue;
                        //    featCls.ClsName = (dlgDataConvert.SourceFeatCls as IDataset).Name;
                        //    featCLses1.Add(featCls);
                        //}
                        //frmNewLog.FeatClses = featCLses1;
                        #endregion

                        doing = true;
                        
                        #endregion

                        break;
                }

                this.Cursor = Cursors.WaitCursor;

                if (dlgDataImport !=null && dlgDataImport.Operate())
                {
                    if (!chkLog.Checked) MsgHelper.ShowInfomationMsgbox("入库操作完毕！");

                    //frmNewLog.IsSucceed = true;
                }
                else
                {
                    if (breaked)
                    {
                        LogHelper.WriteLog("入库被终止。\n");
                        MsgHelper.ShowInfomationMsgbox("入库操作被终止！");
                        breaked = false;
                    }
                    else
                    {
                        MsgHelper.ShowWarningMsgbox("部分或全部数据入库操作失败！详细信息请查看日志。");
                        //frmNewLog.IsSucceed = false;

                    }
                }
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("入库操作失败：" + ex.Message);
                //frmNewLog.IsSucceed = false;
            }
            finally
            {
                this.Cursor = Cursors.Default;

                //if (chkLog.Checked) frmNewLog.ShowDialog();

                //frmNewLog = null;
                dlgDataImportConstruct = null;
                //dlgDataConverts = null;
                dlgDataImport = null;
                //picLoading.Visible = false;
                //progressBarSub.Visible = false;
                //progressBarAll.Visible = false;
                btnStop.Visible = false;
                doing = false;
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click(object sender, EventArgs e)
        {
            if (doing)// && dlgDataImportByCode != null)
            {
                if (MsgHelper.ShowYesOrNoQueryMsgBox("是否要终止入库操作？") == DialogResult.Yes)
                {
                    //if (dlgDataImportConstruct != null) dlgDataImportConstruct.Stop();
                    if (dlgDataImport != null) dlgDataImport.Stop();
                    breaked = true;
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmDlgDataImport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (doing)
            {
                MsgHelper.ShowInfomationMsgbox("入库还未结束，不能退出该窗口！");
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void chkUseGP_Click(object sender, EventArgs e)
        {
            if (chkUseGP.Checked)
            {
                chkDelete.Enabled = false;
            }
            else
            {
                chkDelete.Enabled = true;
            }
        }

        #endregion
    }
}
